/**
 * MapVerse 地图组件主入口文件
 * @description 整合所有功能模块，提供统一的API接口
 */

import { onUnmounted } from 'vue';

import { MapEngine } from './core/mapEngine.js'
import { LayerManager } from './core/LayerManager.ts'

class DrawingTools {
  constructor(engine) {}
  on(event, callback) {}
  drawPoint(options) { return Promise.resolve(null); }
  drawPolyline(options) { return Promise.resolve(null); }
  drawPolygon(options) { return Promise.resolve(null); }
  drawCircle(options) { return Promise.resolve(null); }
  drawRectangle(options) { return Promise.resolve(null); }
  destroy() {}
}

class MeasureTools {
  constructor(engine) {}
  on(event, callback) {}
  measureDistance(options) { return Promise.resolve(null); }
  measureArea(options) { return Promise.resolve(null); }
  measureHeight(options) { return Promise.resolve(null); }
  destroy() {}
}

class MapControls {
  constructor(engine, config) {}
  destroy() {}
}

class MapUtils {
  constructor(engine) {}
  flyToPoint(lng, lat, options) { return Promise.resolve(); }
}

class BusinessLayers {
  constructor(engine, layerManager) {}
  addTowerLayer(options) {}
  addLineLayer(options) {}
  addSubstationLayer(options) {}
  addSensitiveAreaLayer(options) {}
  addSensitiveAnalyseLayer(options) {}
  addVectorTower(options) {}
  addVectorSubStation(options) {}
  removeVectorById(id) {}
  addPolygonJson(options) {}
  addPolylineJson(options) {}
  addPointJson(options) {}
  destroy() {}
}

const mapManager = {
  register: (id, instance) => {},
  unregister: (id) => {}
};

const useMapManager = () => ({});

// MapVerseOptions 配置对象

/**
 * MapVerse 地图组件主类
 */
export class MapVerse {
options;
initialized = false;
destroyed = false;

  // 核心模块实例
engine = null;
layerManager = null;
drawingTools = null;
measureTools = null;
mapControls = null;
mapUtils = null;
businessLayers = null;

  // 事件系统
events = new Map();

  constructor(options = {}) {
    this.options = options;
  }

  /**
   * 初始化MapVerse组件
   */
async initialize(config = {}) {
    if (this.initialized) return this;

    try {
      const finalConfig = { ...this.options, ...config };

      // 初始化各个模块
      this.engine = new MapEngine(finalConfig);
      await this.engine.initialize();

      this.layerManager = new LayerManager(this.engine);
      this.drawingTools = new DrawingTools(this.engine);
      this.measureTools = new MeasureTools(this.engine);
      this.mapControls = new MapControls(this.engine, finalConfig);
      this.mapUtils = new MapUtils(this.engine);
      this.businessLayers = new BusinessLayers(this.engine, this.layerManager);

      // 添加基础图层
      if (finalConfig.addBaseLayers !== false) {
        const baseMapConfig = {
          mapType: finalConfig.mapType || 'offline', // 'offline' | 'online'
          baseMapType: finalConfig.baseMapType || (finalConfig.mapType === 'online' ? 'img' : 'hebei'),
          showAnnotation: finalConfig.showAnnotation !== false,
          tdtToken: finalConfig.tdtToken || '6c99c7793f41fccc4bd595b03711913e'
        };

        this.layerManager.initializeBaseMap(baseMapConfig);
      }

      this.initialized = true;
      this._bindGlobalEvents();
      this.emit('initialized', this);

      return this;
    } catch (error) {
      console.error('MapVerse initialization failed:', error);
      throw error;
    }
  }

  /**
   * 绑定全局事件
   */
  _bindGlobalEvents() {
    if (!this.engine) return;

    this.engine.on('loaded', () => this.emit('mapLoaded'));
    this.engine.on('click', (event) => this.emit('mapClick', event));

    if (this.drawingTools) {
      this.drawingTools.on('drawEnd', (result) => this.emit('drawEnd', result));
    }

    if (this.measureTools) {
      this.measureTools.on('measureEnd', (result) => this.emit('measureEnd', result));
    }
  }

  /**
   * 获取地图实例
   */
getMapInstance() {
    return this.engine?.getInstance() || null;
  }

  /**
   * 飞行到指定位�?   */
flyToPoint(lng, lat, options = {}) {
    return this.mapUtils?.flyToPoint(lng, lat, options) || Promise.reject(new Error('MapUtils not initialized'));
  }

  /**
   * 添加WMS图层
   */
addWmsLayer(options) {
    return this.layerManager?.addWmsLayer(options) || null;
  }

  /**
   * 移除图层
   */
removeLayer(id, destroy = true) {
    return this.layerManager?.removeLayer(id, destroy) || false;
  }

  /**
   * 开始绘�?   */
startDraw(type, options = {}) {
    if (!this.drawingTools) {
      return Promise.reject(new Error('Drawing tools not initialized'));
    }

    const drawMethods = {
      'point': 'drawPoint',
      'line': 'drawPolyline',
      'polyline': 'drawPolyline',
      'polygon': 'drawPolygon',
      'circle': 'drawCircle',
      'rectangle': 'drawRectangle'
    };

    const method = drawMethods[type.toLowerCase()];
    if (method && this.drawingTools[method]) {
      return this.drawingTools[method](options);
    }

    return Promise.reject(new Error(`Unsupported draw type: ${type}`));
  }

  /**
   * 开始测�?   */
startMeasure(type, options = {}) {
    if (!this.measureTools) {
      return Promise.reject(new Error('Measure tools not initialized'));
    }

    const measureMethods = {
      'distance': 'measureDistance',
      'area': 'measureArea',
      'height': 'measureHeight'
    };

    const method = measureMethods[type.toLowerCase()];
    if (method && this.measureTools[method]) {
      return this.measureTools[method](options);
    }

    return Promise.reject(new Error(`Unsupported measure type: ${type}`));
  }

  /**
   * 事件系统
   */
on(event, callback) {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event).push(callback);
  }

emit(event, ...args) {
    if (!this.events.has(event)) return;

    this.events.get(event).forEach(callback => {
      try {
        callback(...args);
      } catch (error) {
        console.error(`Error in event callback for ${event}:`, error);
      }
    });
  }

  /**
   * 切换底图类型
   * @param {Object} options - 底图配置
   * @param {string} options.mapType - 地图类型 ('offline' | 'online')
   * @param {string} options.baseMapType - 底图类型
   * @param {boolean} options.showAnnotation - 是否显示注记
   * @param {string} options.tdtToken - 天地图token
   * @returns {Promise<Array>} 新创建的图层数组
   */
  async switchBaseMap(options = {}) {
    if (!this.layerManager) {
      console.error('LayerManager not initialized');
      return [];
    }

    try {
      const layers = this.layerManager.switchBaseMap(options);
      this.emit('baseMapSwitched', { options, layers });
      return layers;
    } catch (error) {
      console.error('Switch base map failed:', error);
      throw error;
    }
  }

  /**
   * 获取当前底图信息
   * @returns {Array} 当前底图图层信息
   */
  getCurrentBaseMaps() {
    if (!this.layerManager) return [];

    return this.layerManager.getAllLayers().filter(layer =>
      layer.metadata?.baseLayer || layer.metadata?.annotation
    );
  }

  /**
   * 销毁MapVerse组件
   */
destroy() {
    if (this.destroyed) return;

    try {
      this.businessLayers?.destroy();
      this.mapControls?.destroy();
      this.measureTools?.destroy();
      this.drawingTools?.destroy();
      this.layerManager?.destroy();
      this.engine?.destroy();

      this.events.clear();
      this.destroyed = true;
      this.initialized = false;
    } catch (error) {
      console.error('Error destroying MapVerse:', error);
    }
  }
}

// UseMapVerseReturn interface

/**
 * MapVerse 组合函数
 * 不使用Vue响应式系统，避免性能问题
 */
export function useMapVerse(options = {}) {
  // 使用普通变量，不使用ref
  let mapVerse = null;
  let initialized = false;

  const initMapVerse = async (config = {}) => {
    try {
      mapVerse = new MapVerse(options);
      await mapVerse.initialize(config);
      initialized = true;
      return mapVerse;
    } catch (error) {
      console.error('Failed to initialize MapVerse:', error);
      throw error;
    }
  };

  const getMapVerse = () => mapVerse;

  const destroy = () => {
    if (mapVerse) {
      mapVerse.destroy();
      mapVerse = null;
      initialized = false;
    }
  };

  onUnmounted(() => {
    destroy();
  });

  return {
    initMapVerse,
    getMapVerse,
    destroy,
    // 提供状态检查方�?    isInitialized: () => initialized,
    switchBaseMap: async (options) => {
      if (!mapVerse) {
        console.error('MapVerse instance not available');
        return [];
      }
      return await mapVerse.switchBaseMap(options);
    },
    getCurrentBaseMaps: () => {
      if (!mapVerse) {
        console.error('MapVerse instance not available');
        return [];
      }
      return mapVerse.getCurrentBaseMaps();
    }
  };
}

// 导出地图管理器，供外部使�?export { mapManager, useMapManager };

// 导出弹窗组件
export * from './components/popup/index.js';
